package pl.edu.agh.winmon.widget;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.List;

import pl.edu.agh.winmon.hibernate.Process;
import pl.edu.agh.winmon.hibernate.Program;
import pl.edu.agh.winmon.hibernate.Session;

public class ProgramInfoWidget extends SessionUpdatableComposite {

	private List programsList;

	private Map<String, Program> map = new HashMap<String, Program>();

	private ProcessInfoWidget processInfoWidget;

	public ProgramInfoWidget(Composite arg0) {
		super(arg0, SWT.NONE);
		setLayout(new GridLayout(1, true));
		Group programsListGroup = new Group(this, SWT.NONE);
		programsListGroup.setText("Choose program");
		programsListGroup.setLayout(new FillLayout());

		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.heightHint = 50;
		programsListGroup.setLayoutData(gd);

		programsList = new List(programsListGroup, SWT.MULTI | SWT.V_SCROLL);
		programsList.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				processInfoWidget.updateTable();
			}
		});

		processInfoWidget = new ProcessInfoWidget(this) {
			@Override
			public void updateTable() {
				procTable.clearAll();
				procTable.removeAll();
				LinkedList<String[]> listOfRows = new LinkedList<String[]>();
				Collection<Process> processes = new ArrayList<Process>();
				for (String s : programsList.getSelection()) {
					processes.addAll(map.get(s).getProcesses());
				}
				fillUpProcesses(processes, listOfRows);
				data = listOfRows.toArray(new String[][] {});
			}
		};

		processInfoWidget.setLayoutData(new GridData(GridData.FILL_BOTH));
	}

	@Override
	public void updateOnSessionChange(Session session) {
		map.clear();
		programsList.removeAll();
		for (Program p : session.getPrograms()) {
			if (p != null) {
				map.put(p.getName(), p);
				programsList.add(p.getName());
			}
		}
		processInfoWidget.updateOnSessionChange(session);
	}

}
